import urlConfig from './config.js'
import util from './util.js'
const request = {}
const headers = {}
const PORT1 = '/baseinfo'
/*     权限判断 因为有的接口请求头可能需要添加的参数不一样，所以这里做了区分
    1 == 不通过access_token校验的接口
    2 == 文件下载接口列表
    3 == 验证码登录 */
request.globalRequest = (url, method, data, power, msg, domin = 1) => {
	headers['Content-Type'] = 'application/json';
	headers['Product'] = 'sale_mini';
	headers['Version'] = '0.0.1';
	let token = util.$getStorageSync("token");
	console.info("==token===" + token);
	if (token != '' || typeof(token) != undefined) {
		console.log("token===" + token);
		headers["token"] = util.$getStorageSync("token");

	}
	if (power == 1) {
		if (msg) {
			uni.showLoading({
				title: msg
			})
		} else {
			uni.showLoading({
				title: "数据获取中"
			})
		}

	}
	for (var i in data) {
		if (data[i] == undefined) {
			data[i] = '';
		}
	}
	let ymurl = urlConfig;
	if (uni.getStorageSync("$url")) {
		ymurl = uni.getStorageSync("$url");
	}

	var requestUrl = ymurl + url;
	console.info(requestUrl)
	if (domin == 2) {

	}
	return uni.request({
		url: requestUrl,
		method,
		data: data,
		header: headers
	}).then(res => {
		uni.hideLoading();

		console.info("========="+JSON.stringify(res));
		if (res.data.code == 401) {
			console.info("===========需要登录================");

			uni.removeStorageSync("token");
			uni.navigateTo({
					url:'/pages/user/login'
			})
			// uni.navigateTo({
			// 	url:'../signUp/login'
			// })

		}
		return res.data;
	})
}


request.globalRequestW = (url, method, data, power) => {
	headers['Content-Type'] = 'application/json'
	uni.showLoading({
		title: "正在加载",
		mask: true
	})
	let ymurl = urlConfig;
	if (uni.getStorageSync("$url")) {
		ymurl = uni.getStorageSync("$url");
	}
	return uni.request({
		url: ymurl + url,
		method,
		data: data,
		header: headers
	}).then(res => {
		uni.hideLoading();
		console.info("===parmas===" + JSON.stringify(res))

		return res;
	}).catch(parmas => {
		uni.hideLoading();
		console.info("===parmas===" + JSON.stringify(parmas))
		switch (parmas.code) {
			case 401:
				
				console.info("======401=====")
				uni.clearStorageSync()
				uni.navigateTo({
					url:'/pages/login/index'
				})
				break
			default:
				uni.showToast({
					title: parmas.message,
					icon: 'none'
				})
				return Promise.reject()
				break
		}
	})
}

export default request
